import urllib
import utility
import re
import xbmc


#----------------------------------------------------    
#    Configuration class
#----------------------------------------------------

class TV4Config(object):
    BaseUrl = "http://tv4play.se"
    NextPage = "N&#228;sta sida"

#----------------------------------------------------    
#    Factory
#----------------------------------------------------    

class TV4Factory(utility.ParserFactory):
    
    def _getDefaultParser(self):
        return StartParser()

utility.ContentFactory = TV4Factory()

#----------------------------------------------------    
#    TV4 Base parser
#----------------------------------------------------

class TV4Parser(utility.WebParser):

    def onAddItemURL(self, url):
            
        if url[0:4].lower() == "http":
            return url
            
        if url[0] == "/":
            return TV4Config.BaseUrl + url            
        
        if url[0] == "?":                  
            if self.URL.find("?") > 0:
                return self.URL.split("?")[0] + url
           
            return self.URL + '/' + url
               
        return url       

#----------------------------------------------------    
#    Content Parsers
#----------------------------------------------------
    
class StartParser( TV4Parser ):
    """ The first parser executed, provides the data you see 
		when you enter the addon inside xbmc.
	"""
    
    def getDefaultURL(self):
        return TV4Config.BaseUrl
    
    def onParse(self, url, data):
        self._addFolderItem(TV4Config.BaseUrl, "Program A-&#214;", ProgramsAOParser)
        self._addFolderItem(TV4Config.BaseUrl, "Kategorier", CategoryParser)
    
class ProgramsAOParser( TV4Parser ):
    """ Parses the main program A-O list """
    
    def onParse(self, url, data):
        
        contents = re.compile('<div id="contents-container"[\W\w]+?<div id="category-container"').findall(data, re.DOTALL)
        
        if not contents: raise utility.ParserError(url)
        
        #And find all programs here in...
        programs = re.compile('<a href="(?P<curl>[^"]*?)"\sclass="play">(?P<title>[^<]*?)</a>').findall(contents[0], re.DOTALL)
        
        for curl, title in programs:
            self._addFolderItem(curl, title, ProgramParser)
            
class CategoryParser( TV4Parser ):
    """ Parses the main program categories """
    
    def onParse(self, url, data):
    
        #Make a subselection
        contents = re.compile('<div id="category-container"[\W\w]+?<div id="programs-container"').findall(data, re.DOTALL)        
        if not contents: raise utility.ParserError(url)
        
        #And find the categories here in...
        categories = re.compile('<h2>(?P<title>[^<]*?)</h2>').findall(contents[0], re.DOTALL)        
        
        for title in categories:
            #Append category name for later use in CategoryProgramParser
            curl = "%s/?scat=%s" % (url, urllib.quote(title))
            self._addFolderItem(curl, title, CategoryProgramParser)
            
class CategoryProgramParser( TV4Parser ):
    """ Parses programs from the categories """
    
    def onParse(self, url, data):
        
        #Get category name
        category = re.compile('scat=(?P<title>.*)').findall(url, re.DOTALL)        
        if not category: raise utility.ParserError(url)
        
        #Compile a regex with correct category match       
        catRegex = "<h2>%s</h2>([\W\w]+?)<(h2|/div)>" % (urllib.unquote(category[0])) #TODO: match on </div for last category		
    
        if not catRegex: raise utility.ParserError(url)
        
        #Find category section
        contents = re.compile(catRegex).findall(data, re.DOTALL)        
        if not contents: raise utility.ParserError(url)
        
        #Find programs in this category
        programs = re.compile('<a href="(?P<curl>[^"]*?)"\sclass="play">(?P<title>[^<]*?)</a>').findall(contents[0][0], re.DOTALL)
        
        for curl, title in programs:
            self._addFolderItem(curl, title, ProgramParser)
            
class ProgramParser( TV4Parser ):
    
    def onParse(self, url, data):

        categories = re.compile('<a class="{[^}]*?}" href="(?P<url>\?sel[^"]*?)">(?P<title>[^<]*?)</a>').findall(data, re.DOTALL)
        if not categories: raise utility.ParserError(url)

        for curl, title in categories:
            self._addFolderItem(curl, title, ProgramEpisodeParser)
            
class ProgramEpisodeParser( TV4Parser ):
    
    def onParse(self, url, data):

        programs = re.compile('<img src="(?P<imgsrc>[^"]*?\.jpg)"[^>]*?/>[\W\w]+?' + \
                              '<p><a href="(?P<url>[^"]*?)" class="{[^}]*?}">(?P<title>[^<]*?)</a></p>').findall(data, re.DOTALL)

        for image, curl, title in programs:
            if curl.find("anytime.tv4.se") != -1: continue
            xbmc.log(curl)
            self._addImageItem(curl, title.strip(), VideoParser, image)

        nextpage = re.compile('<li\sclass="next\sbutton">[\W\w]+?' + \
                              '<a\shref=".*?/(?P<url>[^"]*?)">').findall(data, re.DOTALL)

        if nextpage:
            self._addFolderItem(nextpage[0], TV4Config.NextPage, ProgramParser)
            
class VideoParser( TV4Parser ):
    
    def onParse(self, url, data):

		# get videoId for current video
        videoId = re.compile('videoId=([^&]+)').findall(url, re.DOTALL)
        if not videoId: raise utility.ParserError(url)

        # download source for contentinfo
        contentInfoUrl = "%s/%s?view=contentinfo" % (TV4Config.BaseUrl, videoId[0])
        contentInfoSource = self._download( contentInfoUrl )

		# get smil id
        vmanProgramId = re.compile('<vmanProgramId>([^>]+)</vmanProgramId>').findall(contentInfoSource, re.DOTALL)
        if not vmanProgramId: raise utility.ParserError(contentInfoUrl)

        #download smil file
        smilUrl = "http://anytime.tv4.se/webtv/metafileFlash.smil?p=%s&bw=1000&emulate=true&sl=true" % (vmanProgramId[0])
        smilSource = self._download( smilUrl )
        
        # get mp4 url from smil file
        mp4Url = re.compile('<video src="([^"]*)').findall(smilSource, re.DOTALL)
        if not mp4Url: raise utility.ParserError(smilUrl)

        # get rtmpe url from smil file        
        rtmpeUrl = re.compile('<meta base="(rtmpe://[^"]*)').findall(smilSource, re.DOTALL)
        if not rtmpeUrl: raise utility.ParserError(smilUrl)
        
        # get swf file location from html source
        swfUrl = re.compile('<link rel="video_src" href="([^"]*)').findall(data, re.DOTALL)
        if not swfUrl: raise utility.ParserError(url)
        
        videoUrl = "%s swfvfy=true swfurl=%stv4playflashlets.swf playpath=%s" % (rtmpeUrl[0], swfUrl[0][0:swfUrl[0].rfind("/") + 1], mp4Url[0])
        
        if not videoUrl: raise utility.ParserError(url)
        self._addVideoItem(videoUrl, "Video")